package com.java.UDP.multicast_socket;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

/**
 * UDP协议组播和广播接收数据：相当于服务端，无需建立连接也可接收数据。先运行服务端再运行客户端发生数据，查看服务端控制台数据接收情况
 * 组播指客户端将数据发送给局域网内一组主机，组播IP地址范围为224.0.0.0-239.255.255.255，其中224.0.0.0-224.0.0.225为预留组播地址
 * 广播指客户端将数据发送给局域网内所有主机，广播IP地址为255.255.255.255
 */
public class MulticastSocketReceive {
    public static void main(String[] args) throws IOException {
        // 创建对象：默认随机绑定可用端口，可通过构造函数传递端口号
        MulticastSocket multicastSocket = new MulticastSocket(8888);

        // joinGroup：将当前主机添加到组播目的地的分组中
        multicastSocket.joinGroup(InetAddress.getByName("224.0.0.1"));

        // receive：接收发送到本机指定端口的数据。该方法会阻塞，直到接收到数据才继续向下运行
        DatagramPacket datagramPacket = new DatagramPacket(new byte[1024], 1024);
        multicastSocket.receive(datagramPacket);
        System.out.println(datagramPacket.getAddress()); // /192.168.2.112
        System.out.println(datagramPacket.getSocketAddress()); // /192.168.2.112:53417
        System.out.println(datagramPacket.getPort()); // 53417
        System.out.println(datagramPacket.getLength()); // 12
        System.out.println(new String(datagramPacket.getData(), datagramPacket.getLength())); // ೤ಽಠ೥ಥಽ೥ಕಊ೯಼ಁఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀఀ

        // close：释放资源
        multicastSocket.close();
    }
}
